//
//  MainMenuViewController.m
//  HotWord
//
//  Created by Rainbow on 8/25/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MainMenuViewController.h"
#import "ChooseLetterViewController.h"
#import "PracticeViewController.h"
#import "CacheData.h"
#import "ChooseLetterViewController.h"
#import "ServiceHelper.h"
#import "HotWordAppDelegate.h"
#import "introduceViewController.h"
#import "PersistenceData.h"
#import "UtilHelper.h"
#import "Reachability.h"

@implementation MainMenuViewController
@synthesize learnBtn;
@synthesize practiceBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [learnBtn release];
    [practiceBtn release];
    [_needDownloadWords release];
    [_updateBtn release];
    [_updateContainer release];
    [_updateInfoLabel release];
    [_propmtInfoView release];
    [_propmtInfoLabel release];
    [_activityView release];
    [_updateCountLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

-(void)returnback
{
    [[PersistenceData sharedData] syncLetterStatus:[CacheData sharedData].selectedLetter];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)updateToolBtn
{   
    HotWordAppDelegate *appDelegate= (HotWordAppDelegate *)[UIApplication sharedApplication].delegate;
    [[appDelegate.MainToolBar viewWithTag:66]removeFromSuperview];
    [[appDelegate.MainToolBar viewWithTag:77]removeFromSuperview];
    [[appDelegate.MainToolBar viewWithTag:88]removeFromSuperview];
    
    UIButton *returnbackBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    returnbackBtn.frame = CGRectMake(-50, 20, 100, 100);
    [returnbackBtn addTarget:self action:@selector(returnback) forControlEvents:UIControlEventTouchUpInside];
    returnbackBtn.tag=77;
    returnbackBtn.alpha=0;
    [returnbackBtn setImage:[UIImage imageNamed:@"back_arrow.png"] forState:UIControlStateNormal];
    [returnbackBtn setImage:[UIImage imageNamed:@"back_arrow.png"] forState:UIControlStateHighlighted];
    [returnbackBtn setBackgroundImage:[UIImage imageNamed:@"tap_light.png"] forState:UIControlStateHighlighted];
    
    [appDelegate.MainToolBar addSubview:returnbackBtn];
    
    learnBtn.alpha = 0;
    practiceBtn.alpha = 0;
    
    if (_updateBtnShowing) {
        [appDelegate.MainToolBar addSubview:self.updateBtn];
        self.updateBtn.alpha = 0;
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [UIView setAnimationDuration:0.2f];
    [UIView setAnimationDelay:0.4f];
    learnBtn.alpha = 1;
    practiceBtn.alpha = 1;
    returnbackBtn.alpha = 1;
    self.propmtInfoLabel.alpha = 1;
    self.propmtInfoView.alpha = 1;
    if (_updateBtnShowing) {
        self.updateContainer.alpha = 1;
        self.updateBtn.alpha = 1;
    }
    [UIView commitAnimations];

}

- (void)downloadWords
{
    NSString *category = nil;
    if ([SAT_WORDS isEqualToString:[CacheData sharedData].currentCategory]) {
        category = @"0";
    }
    else if ([GRE_WORDS isEqualToString:[CacheData sharedData].currentCategory]) {
        category = @"1";
    }
    else if ([IBT_WORDS isEqualToString:[CacheData sharedData].currentCategory]) {
        category = @"2";
    }
    if ([_needDownloadWords count] > 0) {
        NSString *letter = [_needDownloadWords objectAtIndex:0];
        NSMutableDictionary *params = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
        [params setObject:letter forKey:@"letter"];
        
        [params setObject:category forKey:@"category"];
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeGetWords WithParameters:params AndCallBackScope:self AndSuccessSel:@"getLetterSuccess" AndFailedSel:@"getLetterFailed"];
        [_needDownloadWords removeObjectAtIndex:0];
        if (_isUpdating) {
            self.updateInfoLabel.text = [NSString stringWithFormat:@"正在更新：%d/%d，请稍后...\n可以学习或练习，后退将终止更新。", _totalUpdate - [_needDownloadWords count],_totalUpdate];
        }
    }else{
        _updateBtnShowing = YES;
        if (_isUpdating) {
            _isUpdating = NO;
            self.updateInfoLabel.text = @"更新完成";
            [self.updateBtn setBackgroundImage:[UIImage imageNamed:@"check_btn.png"] forState:UIControlStateNormal];
            [self.updateBtn setBackgroundImage:[UIImage imageNamed:@"check_btn.png"] forState:UIControlStateHighlighted];
            self.updateCountLabel.text = [NSString stringWithFormat:@"%d", _totalUpdate];
            self.updateCountLabel.hidden = YES;
            self.activityView.alpha = 0;
            [self.activityView stopAnimating];
        }
        else
        {
            Reachability *reachAblility = [Reachability reachabilityForInternetConnection];
            if (![reachAblility isReachable]) {
                return;
            }
            NSTimeInterval timestamp = [[PersistenceData sharedData] getTimestampByCategory:[CacheData sharedData].currentCategory];
            self.updateInfoLabel.text = [NSString stringWithFormat:@"点按以检查词库更新\n上次更新:%@",[UtilHelper getDateString:timestamp withFormat:@"yyyy/MM/dd"]];
            if (self.navigationController.visibleViewController == self) {
                self.updateBtn.alpha = 0;
                self.updateContainer.alpha = 0;
            }
            [UIView animateWithDuration:0.3
                             animations:^{
                                 if (self.navigationController.visibleViewController == self) {
                                     self.updateContainer.alpha = 1;
                                     self.updateBtn.alpha = 1;
                                 }
                             }];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [((UIButton *)[self.view viewWithTag:444]) setImage:[UIImage imageNamed:@"introduce.png"] forState:UIControlStateNormal];
    _needDownloadWords = [[NSMutableArray alloc] init];
    for (NSString *letterName in [CacheData sharedData].letters) {
        if (![@"A" isEqualToString:letterName]) {
            if (![[CacheData sharedData].savedLetters objectForKey:letterName]) {
                [_needDownloadWords addObject:letterName];
            }
        }
    }
    
    self.updateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.updateBtn setBackgroundImage:[UIImage imageNamed:@"check_btn.png"] forState:UIControlStateNormal];
    [self.updateBtn setBackgroundImage:[UIImage imageNamed:@"check_btn.png"] forState:UIControlStateHighlighted];
    [self.updateBtn setImage:[UIImage imageNamed:@"tap_light.png"] forState:UIControlStateHighlighted];
    [self.updateBtn addTarget:self action:@selector(tapOnUpdateBtn:) forControlEvents:UIControlEventTouchUpInside];
    HotWordAppDelegate *appDelegate= (HotWordAppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate.MainToolBar addSubview:self.updateBtn];
    self.updateBtn.frame = CGRectMake(110, 20, 100, 100);
    self.updateBtn.alpha = 0;
    
    [self downloadWords];
    // Do any additional setup after loading the view from its nib.
}

- (void)getLetterSuccess
{
    if ([_needDownloadWords count] == 0) {
        [self downloadWords];
    }
    else{
        [self performSelector:@selector(downloadWords) withObject:nil afterDelay:5.0f];
    }
}

- (void)getLetterFailed
{
    if ([_needDownloadWords count] > 0) {
        [self downloadWords];
    }
}

- (void)viewDidUnload
{
    [self setLearnBtn:nil];
    [self setPracticeBtn:nil];
    [self setUpdateBtn:nil];
    [self setUpdateContainer:nil];
    [self setUpdateInfoLabel:nil];
    [self setPropmtInfoView:nil];
    [self setPropmtInfoLabel:nil];
    [self setActivityView:nil];
    [self setUpdateCountLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{     
    HotWordAppDelegate *appDelegate= (HotWordAppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.MainToolBar.frame = CGRectMake(0, 410, 320, 70);
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.2f];
    [appDelegate.MainToolBar viewWithTag:66].alpha = 0;
    [appDelegate.MainToolBar viewWithTag:77].alpha = 0;
    [UIView setAnimationDidStopSelector:@selector(updateToolBtn)];
    [UIView commitAnimations];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.updateBtn removeFromSuperview];
}

- (void)viewDidAppear:(BOOL)animated
{
    [[HTActivityIndicator currentIndicator] hide];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)tapOnLearnBtn:(id)sender {
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
    learnBtn.alpha = 0;
    practiceBtn.alpha = 0;
    self.updateBtn.alpha = 0;
    self.propmtInfoLabel.alpha = 0;
    self.propmtInfoView.alpha = 0;
    self.updateContainer.alpha = 0;
    
    HotWordAppDelegate *appDelegate= (HotWordAppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate.MainToolBar viewWithTag:66].alpha = 0;
    [appDelegate.MainToolBar viewWithTag:77].alpha = 0;
    
    [UIView setAnimationDidStopSelector:@selector(moveup)]; 
    [UIView setAnimationDelegate:self];
	[UIView commitAnimations];
}

-(void)moveup
{
    chooseLetterViewController = [[ChooseLetterViewController alloc] init];
    [CacheData sharedData].viewType = HotWordViewTypeLearn;
    [self.navigationController pushViewController:chooseLetterViewController animated:NO];
    [chooseLetterViewController release];
}

- (IBAction)tapOnPracticeBtn:(id)sender {

    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
    learnBtn.alpha = 0;
    practiceBtn.alpha = 0;
    self.updateBtn.alpha = 0;
    self.propmtInfoLabel.alpha = 0;
    self.propmtInfoView.alpha = 0;
    self.updateContainer.alpha = 0;
    
    HotWordAppDelegate *appDelegate= (HotWordAppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate.MainToolBar viewWithTag:66].alpha = 0;
    [appDelegate.MainToolBar viewWithTag:77].alpha = 0;
    [UIView setAnimationDidStopSelector:@selector(movedown)]; 
    [UIView setAnimationDelegate:self];
	[UIView commitAnimations];
}

- (IBAction)tapOnUpdateBtn:(id)sender {
    if (_isUpdating) {
        return;
    }
    NSString *category = nil;
    if ([SAT_WORDS isEqualToString:[CacheData sharedData].currentCategory]) {
        category = @"0";
    }
    else if ([GRE_WORDS isEqualToString:[CacheData sharedData].currentCategory]) {
        category = @"1";
    }
    else if ([IBT_WORDS isEqualToString:[CacheData sharedData].currentCategory]) {
        category = @"2";
    }
    if ([_needDownloadWords count] <= 0) {
        NSMutableDictionary *params = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
        [params setObject:category forKey:@"category"];
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeCheckLetterUpdate WithParameters:params AndCallBackScope:self AndSuccessSel:@"checkUpdateWordSuccess" AndFailedSel:@"checkUpdateWordFailed"];
        self.updateInfoLabel.text = @"正在检查，请稍后...";
        self.updateContainer.userInteractionEnabled = NO;
        self.activityView.alpha = 1;
        [self.activityView startAnimating];
        _isUpdating = YES;
    }
    else{
        NSString *letter = [_needDownloadWords objectAtIndex:0];
        NSMutableDictionary *params = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
        [params setObject:letter forKey:@"letter"];
        [params setObject:category forKey:@"category"];
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeGetWords WithParameters:params AndCallBackScope:self AndSuccessSel:@"getLetterSuccess" AndFailedSel:@"getLetterFailed"];
        [_needDownloadWords removeObjectAtIndex:0];
        self.updateContainer.userInteractionEnabled = NO;
        _isUpdating = YES;
        self.updateInfoLabel.text = [NSString stringWithFormat:@"正在更新：%d/%d，请稍后...\n可以学习或练习，后退将终止更新", _totalUpdate - [_needDownloadWords count],_totalUpdate];
        self.updateCountLabel.text = [NSString stringWithFormat:@"%d", _totalUpdate];
        self.updateCountLabel.hidden = NO;
        self.activityView.alpha = 1;
        [self.activityView startAnimating];
    }
}

-(void)movedown
{
    [CacheData sharedData].viewType = HotWordViewTypePractice;
    chooseLetterViewController = [[ChooseLetterViewController alloc] init];
    
    [self.navigationController pushViewController:chooseLetterViewController animated:NO];
    [chooseLetterViewController release];


}

- (void)checkUpdateWordSuccess
{
    if ([CacheData sharedData].needUpdateLetters && [[CacheData sharedData].needUpdateLetters count] > 0) {
        [_needDownloadWords addObjectsFromArray:[CacheData sharedData].needUpdateLetters];
        _totalUpdate = [_needDownloadWords count];
        self.updateInfoLabel.text = [NSString stringWithFormat:@"共有%d个更新，再次点按以更新。", _totalUpdate];
        [self.updateBtn setBackgroundImage:[UIImage imageNamed:@"updatewords_btn.png"] forState:UIControlStateNormal];
        [self.updateBtn setBackgroundImage:[UIImage imageNamed:@"updatewords_btn.png"] forState:UIControlStateHighlighted];
    }
    else{
        self.updateInfoLabel.text = @"已经是最新的词库";
    }
    self.updateContainer.userInteractionEnabled = YES;
    
    self.activityView.alpha = 0;
    [self.activityView stopAnimating];
    _isUpdating = NO;
}

- (void)checkUpdateWordFailed
{
    self.updateInfoLabel.text = @"检测失败，请重试！";
    self.updateContainer.userInteractionEnabled = YES;
    self.activityView.alpha = 0;
    [self.activityView stopAnimating];
    _isUpdating = NO;
}

@end
